// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command


// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  let weekData = {
    0: [],
    1: [],
    2: [],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
    8: [],
    9: [],
    10: [],
    11: [],
    12: [],
    13: [],
    14: [],
    15: [],
    16: [],
    17: [],
    18: [],
    19: [],
    20: [],
    21: []
  } //最终数据

  let data = await db.collection('user') //查询学号
    .where({
      id: wxContext.OPENID
    }).get()
  let termData = data.data[0].skrw[event.selectTerm] //上课任务数据

  if (!termData) {
    return 404
  }
  for (let index = 0; index < termData.length; index++) {
    const item = termData[index];
    let classData = await db.collection('kb_' + event.selectTerm) //从课表中查询数据
      .where({
        id: item.id,
        classmate: item.classmate
      }).get()
    classData.data.forEach(element => { //数据导入
      let y = parseInt(element.section.slice(0, 2))
      let p = [element.whatDay.toString(), y, element.section.length / 2]
      weekData[element.week - 1].push({
        address: element.address, //学分
        name: element.name, //课程名称
        classmate: element.classmate, //教学班名称
        mateNum: element.mateNum, //上课人数
        teacher: element.teacher, //授课教师  
        type: element.type, //上课类型  
        context: element.context, //授课内容简介  
        destination: element.destination, //上课地点
        position: p,
        color: "text" + (index % 8).toString()
      })
    })
  }
  // termData.forEach(item => {

  // })

  return weekData
}